package com.sharemarking.wa.platform.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sharemarking.wa.platform.service.HttpWechatOnlyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@Service
public class HttpWechatOnlyServiceImpl implements HttpWechatOnlyService {
	
	private Logger logger= LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ObjectMapper om;
	
	private void closeAll(Closeable... closables) {
		for(Closeable c:closables) {
			try {
				if(c!=null)c.close();
			}catch(IOException ioe) {
				logger.error("关闭流错误", ioe);
				ioe.printStackTrace();
			}
		}
	}
	
	@Override
	public <RES> RES getJSON(String url,Class<RES> resClass) {
		URL u=null;
		try {
			u=new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		HttpURLConnection conn=null;
		InputStream is=null;
		RES res=null;
		try {
			conn=(HttpURLConnection)u.openConnection();
			is=conn.getInputStream();
			if(conn.getResponseCode()>=300) {
				throw new RuntimeException("微信服务器错误");
			}
			res=om.readValue(is, resClass);
			conn.disconnect();
		} catch (IOException ioe) {
			logger.error("连接失败", ioe);
		} finally {
			closeAll(is);
		}
		return res;
	}

	@Override
	public <REQ, RES> RES postJSON(String url, REQ req, Class<RES> resClass) {
		URL u=null;
		try {
			u=new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		HttpURLConnection conn=null;
		OutputStream os=null;
		InputStream is=null;
		RES res=null;
		try {
			conn=(HttpURLConnection)u.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			os=conn.getOutputStream();
			om.writeValue(os, req);
			os.flush();
			is=conn.getInputStream();
			if(conn.getResponseCode()>=300) {
				throw new RuntimeException("微信服务器错误");
			}
			res=om.readValue(is, resClass);
			conn.disconnect();
		} catch (IOException ioe) {
			logger.error("连接失败", ioe);
		} finally {
			closeAll(is,os);
		}
		return res;
	}

	
	
	
}
